package cj.web.uc.controllers;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.MD5Security;
import cj.utils.weixin.HttpsWenXinUtil;
import cj.web.cc.controllers.BaseController;
import cj.web.constants.MemuEnum;
import cj.web.sc.dao.AppTokenDAO;
import cj.web.sc.dao.OrderDAO;
import cj.web.uc.dao.LoginDAO;

@Path("user")
public class LoginController extends BaseController{
	@Autowired
	private LoginDAO loginDao;
	@Autowired
	private AppTokenDAO appTokenDao;
	@Autowired
	private OrderDAO orderDao;
	
	/**
	 * 登录页过验证
	 * @param model
	 * @param returnPage
	 * @return
	 * @throws Exception 
	 */
	@Get("loginpage")
	public String loginpage(Model model,HttpServletRequest request,HttpServletResponse response) throws Exception{
		model.add("currentTopMemu", MemuEnum.memulogin);
		String returnPage = getCookieValueByName(request,"returnPage");
		String agree = getCookieValueByName(request,"agree");//是否同意
		
		//Cookie中移除returnPage
		removeCookie(response, "agree");
		
		if(returnPage != null && returnPage.length() > 0){
			model.add("returnPage", returnPage);
		}else{
			model.add("returnPage", "/user/myPc");
		}
		
		if(agree!=null && !"".equals(agree)){
			model.add("toRegister", true);
		}else{
			model.add("toRegister", false);
		}
		
		return "/views/uc/loginTemp.vm";
	}
	
	/**
	 * 登录页
	 * @param model
	 * @param returnPage
	 * @return
	 * @throws Exception 
	 */
	@Get("loginPage")
	public String loginPage(Model model,HttpServletRequest request,HttpServletResponse response) throws Exception{
		model.add("currentTopMemu", MemuEnum.memulogin);
		String returnPage = getCookieValueByName(request,"returnPage");
		String agree = getCookieValueByName(request,"agree");//是否同意
		
		//Cookie中移除returnPage
		removeCookie(response, "agree");
		
		if(returnPage != null && returnPage.length() > 0){
			model.add("returnPage", returnPage);
		}else{
			model.add("returnPage", "/user/myPc");
		}
		
		if(agree!=null && !"".equals(agree)){
			model.add("toRegister", true);
		}else{
			model.add("toRegister", false);
		}
		
		return "/views/uc/login.vm";
	}
	
	/**
	 * 登录方法
	 * @param phone
	 * @param pwd
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Post("login")//phone memberId
	public String login(@Param("phone")String phone,
			@Param("pwd")String pwd,HttpServletResponse response) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		if(phone!=null){
			
			List<Map> reps = loginDao.getMemberByPhone(phone);
			
			if(reps.size()>0 && reps.size()==1){
				String l_pwd = reps.get(0).get("pwd").toString();
				String memberId = reps.get(0).get("id").toString();
				String sex = reps.get(0).get("sex").toString();
				if(l_pwd.equals(MD5Security.md5(pwd))){
					//密码相等
					setCookie(response, "phone", phone);//电话号码
					setCookie(response, "memberId", memberId);//用户ID
					setCookie(response, "sex", sex);//性别
					//种植的Key
					setCookie(response, "_token_", MD5Security.returnSingKey(phone+memberId+KEY_TOKEN_));//种植的Key
					//Cookie中移除returnPage
					removeCookie(response, "returnPage");
				}else{
					//密码错误
					jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
					jo.put("returnCode", Constants.returnObj.returnCode.code_1);
				}
				
			}else{
				//不存在此用户
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_2);
			}
			
			
		}else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 注册方法
	 * @param phone
	 * @param token
	 * @param pwd
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@Post("register")
	public String register(@Param("phone")String phone, @Param("token")String token
			, @Param("pwd")String pwd, HttpServletResponse response) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		int memberId =0;
		
		//boolean flag = appTokenDao.queryToken(phone, token)>0;
		
		boolean flag = true;
		
		if(flag){
			List<Map> uc = loginDao.getMemberByPhone(phone);
			if(uc.size() == 0){
				//不存在
				memberId = loginDao.register(phone,MD5Security.md5(pwd),null);
				setCookie(response, "phone", phone);//电话号码
				setCookie(response, "memberId", String.valueOf(memberId));//用户ID
				appTokenDao.updateToken(phone);
			}else if(uc.size()>0){
				//存在
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_1);
			}
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 楚才用户使用协议
	 * @return
	 */
	@Get("agreeMent")
	public String agreeMent(Model model){
		model.add("currentTopMemu", MemuEnum.memulogin);
		return "/views/apply/agreement.vm";
	}
	
	@Get("agree")
	public String agree(Model model, HttpServletResponse response){
		model.add("currentTopMemu", MemuEnum.memulogin);
		setCookie(response, "agree", "agree");//电话号码
		return "r:loginPage";
	}
	
	/**
	 * 找回密码页面
	 * @return
	 */
	@Get("forgetPwdPage")
	public String forgetPwdPage(Model model){
		model.add("currentTopMemu", MemuEnum.memulogin);
		return "/views/uc/forgetPwd.vm";
	}
	
	/**
	 * 找回密码
	 * @param phone
	 * @param token
	 * @param pwd
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Post("forgetPwd")
	public String forgetPwd(@Param("phone")String phone, @Param("token")String token
			, @Param("pwd")String pwd, HttpServletResponse response) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> uc = loginDao.getMemberByPhone(phone);
		if(uc.size() == 0){
			//不存在
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_2);
		}else if(uc.size()>0){
			
			//boolean flag = appTokenDao.queryToken(phone, token)>0;
			
			boolean flag = true;
			
			//存在
			if(flag){
				
				int memberId = Integer.parseInt(uc.get(0).get("id").toString());//userId
				
				loginDao.updateMemberId(memberId, MD5Security.md5(pwd));
				appTokenDao.updateToken(phone);
			}
			else{
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			}
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 登出
	 * @param response
	 * @return
	 */
	@Get("logout")
	public String logout(Model model,HttpServletResponse response){
		removeCookie(response,"phone");
		removeCookie(response,"memberId");
		removeCookie(response,"_token_");
		//Cookie中移除returnPage
		removeCookie(response, "returnPage");
		return "r:my";
	}
	
	/**
	 * 登出
	 * @param response
	 * @return
	 */
	@Get("logoutPc")
	public String logoutPc(Model model,HttpServletResponse response){
		removeCookie(response,"phone");
		removeCookie(response,"memberId");
		removeCookie(response,"_token_");
		//Cookie中移除returnPage
		removeCookie(response, "returnPage");
		return "r:myPc";
	}
	
	@Get("myCode")  //登录Code
	public String myCode(Model model,@Param("code")String code, HttpServletResponse response){
		String openId = HttpsWenXinUtil.retOpenId(code,APPID,APPSECRET);
//		String openId = "ofwuNsyVHbXdpotCwZ_ZJLp7DSrQ";
		setCookie(response, "openId", openId);
		return "r:my";
	}
	
	/**
	 * 用户中心
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@Get("my")
	public String my(Model model, HttpServletRequest request) throws Exception{
		if(isLogin(request)){
			String phone = getCookieValueByName(request, "phone");
			String memberId = getCookieValueByName(request, "memberId");
			model.add("memberId", memberId);
			model.add("phone", phone);
			model.add("isLogin", true);
		}else{
			model.add("isLogin", false);
		}
		model.add("currentTopMemu", MemuEnum.memugrzx);
		
		//--------------微信签名
		Map<String, String> config = getConfigSign(request);
		model.add("Config",config);
				
		return "/views/uc/wx/userCenter.vm";
	}
	
	/**
	 * 用户中心
	 * @param model
	 * @param request
	 * @return
	 */
	@Get("myPc")
	public String myPc(Model model, HttpServletRequest request){
		if(isLogin(request)){
			String phone = getCookieValueByName(request, "phone");
			String memberId = getCookieValueByName(request, "memberId");
			model.add("memberId", memberId);
			model.add("phone", phone);
			model.add("isLogin", true);
		}else{
			model.add("isLogin", false);
		}
		model.add("currentMemu", MemuEnum.wdbm);
		model.add("currentTopMemu", MemuEnum.memugrzx);
		return "/views/uc/userCenter.vm";
	}
	
	private int getBuyerId(HttpServletRequest request){
    	String phone = getCookieValueByName(request, "phone");
		int buyerId = loginDao.getBuyerId(phone);
		
		return buyerId;
    }
	
	/**
	 * 关于我们
	 * @return
	 */
	@Get("aboutus")
	public String aboutUs(Model model){
		model.add("currentTopMemu", MemuEnum.memugrzx);
		return "/views/uc/wx/aboutUs.vm";
	}
	
	/**
	 * 关于我们
	 * @return
	 */
	@Get("aboutusPc")
	public String aboutusPc(Model model, HttpServletRequest request){
		if(isLogin(request)){
			String phone = getCookieValueByName(request, "phone");
			String memberId = getCookieValueByName(request, "memberId");
			model.add("memberId", memberId);
			model.add("phone", phone);
			model.add("isLogin", true);
			
		}else{
			model.add("isLogin", false);
		}
		model.add("currentMemu", MemuEnum.gywm);
		model.add("currentTopMemu", MemuEnum.memugrzx);
		return "/views/uc/aboutUs.vm";
	}
}